<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Category\Category;
use Illuminate\Support\Facades\DB;

class CategoryModuleMenuSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $existingMenu = DB::table('admin_menu')->where('title', '书籍管理')->first();
        if (!$existingMenu) {
            $this->command->info('ℹ️ "书籍管理"菜单不存在，跳过执行');
            return;
        }

        $parentMenuId = $existingMenu->id;
        $existingSubMenu = DB::table('admin_menu')
            ->where('title', '书籍模块')
            ->where('parent_id', $parentMenuId)
            ->first();

        if ($existingSubMenu) {
            $this->command->info('ℹ️ "书籍模块"子菜单已存在，跳过创建');
        } else {
            // 创建子菜单
            DB::table('admin_menu')->insert([
                'parent_id' => $parentMenuId,
                'order' => $this->getNextOrder($parentMenuId),
                'title' => '书籍模块',
                'icon' => 'fa-list',
                'uri' => '/category_module',
                'extension' => '',
                'show' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            $this->command->info('书籍模块数据填充完成！');
        }
    }

    protected function getNextOrder($parentId)
    {
        $maxOrder = DB::table('admin_menu')
            ->where('parent_id', $parentId)
            ->max('order');

        return $maxOrder ? $maxOrder + 1 : 1;
    }
}
